"use server"
import { Avatar, Button, Card } from "antd"
import { getQuestionBankVOById } from "@/api/question-bank"
import Meta from "antd/es/card/Meta"
import Paragraph from "antd/es/typography/Paragraph"
import Title from "antd/es/typography/Title"
import QuestionList from "@/components/question-list"
import "./index.css"

interface Props {
  params: {
    questionBankId: number // 题库ID
  }
}

/**
 * 题库详情页
 */
export default async function BankPage({ params }: Props) {
  const { questionBankId } = params

  let bank: QuestionBankVO | null = null

  try {
    const res = await getQuestionBankVOById({
      id: questionBankId,
      needQueryQuestionList: true,
      pageSize: 200
    })
    bank = res.data
  } catch (error) {
    console.error("获取题库详情失败，" + error)
  }

  if (!bank) {
    return <div>获取题库详情失败，请刷新重试</div>
  }

  // 获取第一条题目，用于开始刷题按钮的点击跳转
  let firstQuestionId
  if (bank.questionPage?.records && bank.questionPage.records.length > 0) {
    firstQuestionId = bank.questionPage.records[0].id
  }

  return (
    <div id="bankPage" className="max-width-content">
      <Card>
        <Meta
          avatar={<Avatar src={bank.picture} size={72} />}
          title={
            <Title level={3} style={{ marginBottom: 0 }}>
              {bank.title}
            </Title>
          }
          description={
            <>
              <Paragraph type="secondary">{bank.description}</Paragraph>
              <Button
                type="primary"
                shape="round"
                href={`/bank/${questionBankId}/question/${firstQuestionId}`}
                target="_blank"
                disabled={!firstQuestionId}
              >
                开始刷题
              </Button>
            </>
          }
        />
      </Card>
      <div style={{ marginBottom: 16 }} />
      <QuestionList
        questionBankId={questionBankId}
        questionList={bank.questionPage?.records ?? []}
        cardTitle={`题目列表 (${bank.questionPage?.total || 0})`}
      />
    </div>
  )
}
